package com.easylinkin.linkappapi.inspection.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.circuit.dto.RailGiveAlarmTypeConfigEnum;
import com.easylinkin.linkappapi.circuit.service.IRailGiveSystemAlarmService;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.config.service.SysDictService;
import com.easylinkin.linkappapi.device.constant.DeviceConstant.ModelCategoryEnum;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.entity.ElectricyRecords;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.device.util.DeviceUtil;
import com.easylinkin.linkappapi.inspection.dto.ElectricBoxRecordDTO;
import com.easylinkin.linkappapi.inspection.entity.ElectricBox;
import com.easylinkin.linkappapi.inspection.entity.ElectricBoxRecord;
import com.easylinkin.linkappapi.inspection.mapper.ElectricBoxMapper;
import com.easylinkin.linkappapi.inspection.mapper.ElectricBoxRecordMapper;
import com.easylinkin.linkappapi.inspection.service.ElectricBoxRecordService;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 配电箱数据记录 服务实现类
 * </p>
 *
 * @author Xiaoyang
 * @since 2022-08-17
 */
@Service
@Slf4j
public class ElectricBoxRecordServiceImpl extends ServiceImpl<ElectricBoxRecordMapper, ElectricBoxRecord> implements ElectricBoxRecordService {

  @Autowired
  private DeviceService deviceService;

  @Resource
  private ElectricBoxMapper electricBoxMapper;

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;

  @Autowired
  private IRailGiveSystemAlarmService railGiveSystemAlarmService;

  @Autowired
  private SysDictService sysDictService;
  @Autowired
  private SysDictItemService dictItemService;


  @Override
  public List<ElectricBoxRecord> getList(ElectricBoxRecordDTO recordDTO) {
    // 构造结果数据
    List<ElectricBoxRecord> result = new ArrayList<>();
    //前端不要这种为0的数据，我也很无奈
//    List<Date> timeList = null;
//    try {
//      timeList = DateUtil.findDates(recordDTO.getStartTime(), recordDTO.getEndTime());
//      if (CollectionUtil.isEmpty(timeList)) {
//        return null;
//      }else{
//        timeList.forEach(p->{
//          ElectricBoxRecord record = new ElectricBoxRecord();
//          record.setCreateTime(p);
//          record.setTemperature1(0d);
//          record.setTemperature2(0d);
//          record.setTemperature3(0d);
//          record.setTemperature4(0d);
//          record.setResidualCurrent(0d);
//          record.setActivePower(0d);
//          result.add(record);
//        });
//      }
//    } catch (ParseException e) {
//      log.error("getList 配电箱数据记录 时间转换异常");
//      throw new RuntimeException("getList 配电箱数据记录 时间转换异常" + e.getMessage());
//    }
    recordDTO.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    List<ElectricBoxRecord> list = baseMapper.getList(recordDTO);
    if(CollectionUtil.isNotEmpty(list)){
      return list;
    }
    return result;
  }

  @Override
  public void datapushHandler(DatapushDTO datapushDTO) {
    // 流水处理流程
    JSONObject data = datapushDTO.getData();
//    String deviceCode = datapushDTO.getDevice_id();
//      Device device = new Device();
//      device.setCode(deviceCode);
//      List<Device> deviceList = deviceService.selectDevices(device);
//      if (deviceList == null || deviceList.size() <= 0) {
//        return ;
//      }
//      device = deviceList.get(0);

    // 将查询逻辑放入主线程
    Device device = datapushDTO.getDevice_data_latest();

    if(!DeviceUtil.isBelongSpecifiedDeviceType(device,ModelCategoryEnum.ELECTRIC_BOX.getDeviceTypeNameKey())){
      return ;
    }
    QueryWrapper<ElectricBox> queryWrapper = new QueryWrapper();
    queryWrapper.eq("tenant_id_",device.getTenantId())
        .eq("monitor_device_code_",device.getCode())
        .eq("is_delete_",0);

    ElectricBox electricBox = electricBoxMapper.selectOne(queryWrapper);
    if(null == electricBox){
      return ;
    }
    // 当前累计流量
    Double activePower = data.getDouble("active_power");
    Double residualCurrent = data.getDouble("residual_current");
    Double temperature_1 = data.getDouble("temperature_1");
    Double temperature_2 = data.getDouble("temperature_2");
    Double temperature_3 = data.getDouble("temperature_3");
    Double temperature_4 = data.getDouble("temperature_4");
    if (null == activePower || null == residualCurrent || null == temperature_1
        || null == temperature_2 || null == temperature_3 || null == temperature_4) {
      return;
    }
    ElectricBoxRecord electricBoxRecord = new ElectricBoxRecord();
    electricBoxRecord.setCreateTime(new Date());
    electricBoxRecord.setElectricBoxId(electricBox.getId());
    electricBoxRecord.setDeviceCode(device.getCode());
    electricBoxRecord.setTenantId(device.getTenantId());
    electricBoxRecord.setActivePower(activePower);
    electricBoxRecord.setResidualCurrent(residualCurrent);
    electricBoxRecord.setTemperature1(temperature_1);
    electricBoxRecord.setTemperature2(temperature_2);
    electricBoxRecord.setTemperature3(temperature_3);
    electricBoxRecord.setTemperature4(temperature_4);
    baseMapper.insert(electricBoxRecord);
  }

  @Override
  public Map<String, Object> boxRecordByhoursOrMonthly(ElectricBoxRecordDTO electricBoxRecordDTO) {
    String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
    electricBoxRecordDTO.setTenantId(tenantId);
    Map<String, Object> result = new HashMap<>();
    List<String> range = null;
    List<ElectricBoxRecord> electricBoxRecords = null;
    switch (electricBoxRecordDTO.getDailyOrMonthly()){
      case 0:
        //24小时
        range = DateUtil.getLast24HoursRange(DateUtil.getYYYYMMDDDate(new Date()));
        electricBoxRecordDTO.setStartTimeH(range.get(0));
        electricBoxRecordDTO.setEndTimeH(range.get(range.size()-1));
        electricBoxRecords = baseMapper.selectByDateOrTime(electricBoxRecordDTO);
        break;
      case 1:
        //30天
        range = DateUtil.getLast30Days();
        electricBoxRecordDTO.setStartTime(range.get(0));
        electricBoxRecordDTO.setEndTime(range.get(range.size()-1));
        electricBoxRecords = baseMapper.selectByDateOrTime(electricBoxRecordDTO);
        break;
      default:
        break;
    }
    if (Objects.isNull(range)){
      return result;
    }
    //遍历
    List<ElectricBoxRecord> transferStation = new ArrayList<>();
    List<Double> temperature_1_array = new ArrayList<>();
    List<Double> temperature_2_array = new ArrayList<>();
    List<Double> temperature_3_array = new ArrayList<>();
    List<Double> temperature_4_array = new ArrayList<>();
    List<Double> residualCurrentArray = new ArrayList<>();
    boolean zero = false;
    List<String> abscissa = new ArrayList<>();
    for (String  ran_Time:range){
      Double  temperature1 = 0.00;
      Double  temperature2 = 0.00;
      Double  temperature3 = 0.00;
      Double  temperature4 = 0.00;
      Double  residualCurrent = 0.00;
      if (zero) {
        temperature_1_array.add(temperature1);
        temperature_2_array.add(temperature2);
        temperature_3_array.add(temperature3);
        temperature_4_array.add(temperature4);
        residualCurrentArray.add(residualCurrent);
        abscissa.add(ran_Time);
        continue;
      }
      if (transferStation.size() == 0 ){
        int leftIndex = 0;
        int rightIndex  = electricBoxRecords.size()-1;
        while (leftIndex<=rightIndex){
          if (leftIndex == rightIndex){
            ElectricBoxRecord leftRecords = electricBoxRecords.get(leftIndex);
            String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
            if (leftCollectTime.startsWith(ran_Time)){
              temperature1 = (Objects.isNull(leftRecords.getTemperature1())?0.0:leftRecords.getTemperature1());
              temperature2 = (Objects.isNull(leftRecords.getTemperature2())?0.0:leftRecords.getTemperature2());
              temperature3 = (Objects.isNull(leftRecords.getTemperature3())?0.0:leftRecords.getTemperature3());
              temperature4 = (Objects.isNull(leftRecords.getTemperature4())?0.0:leftRecords.getTemperature4());
              residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
            }else{
              transferStation.add(leftRecords);
            }
            break;
          }
          ElectricBoxRecord leftRecords = electricBoxRecords.get(leftIndex);
          String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
          if (leftCollectTime.startsWith(ran_Time)){
            temperature1 = (Objects.isNull(leftRecords.getTemperature1())?0.0:leftRecords.getTemperature1());
            temperature2 = (Objects.isNull(leftRecords.getTemperature2())?0.0:leftRecords.getTemperature2());
            temperature3 = (Objects.isNull(leftRecords.getTemperature3())?0.0:leftRecords.getTemperature3());
            temperature4 = (Objects.isNull(leftRecords.getTemperature4())?0.0:leftRecords.getTemperature4());
            residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
          }else{
            transferStation.add(leftRecords);
          }
          leftIndex++;
          ElectricBoxRecord rightRecords = electricBoxRecords.get(rightIndex);
          String rightCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(rightRecords.getCreateTime());
          if (rightCollectTime.startsWith(ran_Time)){
            temperature1 = (Objects.isNull(rightRecords.getTemperature1())?0.0:rightRecords.getTemperature1())+temperature1;
            temperature2 = (Objects.isNull(rightRecords.getTemperature2())?0.0:rightRecords.getTemperature2())+temperature2;
            temperature3 = (Objects.isNull(rightRecords.getTemperature3())?0.0:rightRecords.getTemperature3())+temperature3;
            temperature4 = (Objects.isNull(rightRecords.getTemperature4())?0.0:rightRecords.getTemperature4())+temperature4;
            residualCurrent = (Objects.isNull(rightRecords.getResidualCurrent())?0.0:rightRecords.getResidualCurrent())+residualCurrent;
          }else{
            transferStation.add(rightRecords);
          }
          rightIndex--;
        }
      }else{
        List<ElectricBoxRecord> letw = transferStation;
        transferStation = new ArrayList<>();
        int leftIndex = 0;
        int rightIndex  = letw.size()-1;
        while (leftIndex<=rightIndex) {
          if (leftIndex == rightIndex){
            ElectricBoxRecord leftRecords = letw.get(leftIndex);
            String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
            if (leftCollectTime.startsWith(ran_Time)){
              temperature1 = (Objects.isNull(leftRecords.getTemperature1())?0.0:leftRecords.getTemperature1());
              temperature2 = (Objects.isNull(leftRecords.getTemperature2())?0.0:leftRecords.getTemperature2());
              temperature3 = (Objects.isNull(leftRecords.getTemperature3())?0.0:leftRecords.getTemperature3());
              temperature4 = (Objects.isNull(leftRecords.getTemperature4())?0.0:leftRecords.getTemperature4());
              residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
            }else{
              transferStation.add(leftRecords);
            }
            break;
          }
          ElectricBoxRecord leftRecords = letw.get(leftIndex);
          String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
          if (leftCollectTime.startsWith(ran_Time)){
            temperature1 = (Objects.isNull(leftRecords.getTemperature1())?0.0:leftRecords.getTemperature1());
            temperature2 = (Objects.isNull(leftRecords.getTemperature2())?0.0:leftRecords.getTemperature2());
            temperature3 = (Objects.isNull(leftRecords.getTemperature3())?0.0:leftRecords.getTemperature3());
            temperature4 = (Objects.isNull(leftRecords.getTemperature4())?0.0:leftRecords.getTemperature4());
            residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
          }else{
            transferStation.add(leftRecords);
          }
          leftIndex++;
          ElectricBoxRecord rightRecords = letw.get(rightIndex);
          String rightCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(rightRecords.getCreateTime());
          if (rightCollectTime.startsWith(ran_Time)){
            temperature1 = (Objects.isNull(rightRecords.getTemperature1())?0.0:rightRecords.getTemperature1());
            temperature2 = (Objects.isNull(rightRecords.getTemperature2())?0.0:rightRecords.getTemperature2());
            temperature3 = (Objects.isNull(rightRecords.getTemperature3())?0.0:rightRecords.getTemperature3());
            temperature4 = (Objects.isNull(rightRecords.getTemperature4())?0.0:rightRecords.getTemperature4());
            residualCurrent = (Objects.isNull(rightRecords.getResidualCurrent())?0.0:rightRecords.getResidualCurrent())+residualCurrent;
          }else{
            transferStation.add(rightRecords);
          }
          rightIndex--;
        }
        }
      if (transferStation.size() == 0) {
        zero = true;
      }
      temperature_1_array.add(temperature1);
      temperature_2_array.add(temperature2);
      temperature_3_array.add(temperature3);
      temperature_4_array.add(temperature4);
      residualCurrentArray.add(residualCurrent);
      abscissa.add(ran_Time);
      }
      result.put("tempUnit","°C");
      result.put("electricUnit","A");
      result.put("temperature_1_array",temperature_1_array);
      result.put("temperature_2_array",temperature_2_array);
      result.put("temperature_3_array",temperature_3_array);
      result.put("temperature_4_array",temperature_4_array);
      result.put("residualCurrentArray",residualCurrentArray);
      result.put("abscissa",abscissa);
      return result;
  }
}
